/**
 * 功能：格式化时间
 */
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

//#region 时间对象的格式化
/**
 * @param {*} datatime 时间参数
 * @param {*} formatstr 格式化字符串
 */
function DateTimeFormat(datatime, formatstr) {
  return datatime.format(formatstr);
// 调用方法:
// var times = 1290371638000;//时间戳，可以是一个具体的时间
// var testDate = new Date(times);
// var testStr = testDate.format("yyyy年MM月dd日hh小时mm分ss秒");
// var testStr2 = testDate.format("yyyy-MM-dd");
}

/*
* 时间对象的格式化;
*/
Date.prototype.format = function (format) {
  /*
  * eg:format="yyyy-MM-dd hh:mm:ss";
  */
  var o = {
      "M+": this.getMonth() + 1, //month
      "d+": this.getDate(),   //day
      "H+": this.getHours(),  //hour
      "m+": this.getMinutes(), //minute
      "s+": this.getSeconds(), //second
      "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
      "S": this.getMilliseconds() //millisecond
  }

  if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
  }
  return format;
}
//#endregion


module.exports = {
  formatTime,
  DateTimeFormat
}
